import { request } from '@/app/http'
import { toPageParam, toPageResult, toRangeParam } from 'app/converter'
import { encrypt } from '@/utils'

const PATH = '/users'

export async function searchUser(params, pageData) {
  const { data } = await request({
    url: PATH,
    method: 'get',
    params: { ...toRangeParam(params), ...toPageParam(pageData) }
  })
  return toPageResult(data)
}

export function addUser(data) {
  return request({
    url: PATH,
    method: 'post',
    data
  })
}

export function updateUser(data) {
  return request({
    url: PATH,
    method: 'put',
    data
  })
}

export function removeUser(data) {
  return request({
    url: PATH,
    method: 'delete',
    data,
    showLoading: true,
    showMsg: true
  })
}

export function downloadUser(params) {
  return request({
    url: PATH + '/download',
    method: 'get',
    params,
    responseType: 'blob',
    showLoading: true,
    showMsg: true
  })
}

export function updateAvatar(params) {
  const { avatarId } = params
  if (!avatarId) {
    return Promise.reject({ msg: '请上传头像' })
  }
  return request({
    url: PATH + '/updateAvatar',
    method: 'get',
    params
  })
}

export function updateEmail(params) {
  const data = { ...params }
  data.password = encrypt(data.password)
  return request({
    url: PATH + '/updateEmail',
    method: 'post',
    data
  })
}

export function updatePass(data) {
  const { oldPass, newPass, confirmPass } = data
  if (newPass !== confirmPass) {
    return Promise.reject({ msg: '确认密码和新密码不一致' })
  }
  return request({
    url: PATH + '/updatePass',
    method: 'post',
    data: {
      oldPass: encrypt(oldPass),
      newPass: encrypt(newPass)
    }
  })
}

export function updateUserCenter(data) {
  return request({
    url: PATH + '/center',
    method: 'put',
    data
  })
}
